﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Renren.Models;
using Renren.Services;

namespace Renren.ViewModels
{
    public class CachedCollection<VMT, MT> : ObservableCollection<VMT> where VMT : ViewModel<MT>, new() where MT : Model
    {
        private const int addedCountThreshold = 10;
        private int addedCount = 0;

        public void Refresh(List<MT> models)
        {
            addedCount = 0;
            for (int i = 0; i < models.Count; i++)
            {
                if (i < this.Count)
                {
                    this[i].Model = models[i];
                }
                else
                {
                    VMT viewModel = new VMT();
                    viewModel.Model = models[i];
                    this.Add(viewModel);
                }
            }
            // If displayed size is larger than cached size, shrink the displayed size
            if (models.Count < this.Count)
            {
                int removeCount = this.Count - models.Count;
                for (int i = 0; i < removeCount; i++)
                {
                    this.RemoveAt(models.Count);
                }
            }
        }

        public bool Add(List<MT> models)
        {
            foreach (var model in models)
            {
                // Add a new view model if the model is not found
                if (this.Count(viewModel => viewModel.Id == model.Id) == 0)
                {
                    VMT viewModel = new VMT();
                    viewModel.Model = model;
                    this.Add(viewModel);
                    addedCount++;
                }
            }
            if (addedCount >= addedCountThreshold)
            {
                addedCount = 0;
                return true;
            }
            return false;
        }
    }
}
